<?php
function text_time($time){
    $span = time() - $time;
    if($span > 86400){
        return ceil($span / 86400) . '天前';
    }elseif($span > 3600){
        return ceil($span / 3600) . '小时前';
    }elseif($span > 60){
        return ceil($span / 60) . '分钟前';
    }else{
        return $span . '秒前';
    }
}

function saddslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = saddslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	
	$ckey_length = 4;	
	$key = md5($key ? $key : UC_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	
	$result = '';
	$box = range(0, 255);
	
	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	
	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

function isemail($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

function inputFilter($str)
{
	if(empty($str) && $str!=0)
	{
		return '';
	}
	$str=trim($str);
	$str=str_ireplace("&","&amp;",$str);
	$str=str_ireplace(">","&gt;",$str);
	$str=str_ireplace("<","&lt;",$str);
	$str=str_ireplace(chr(34),"&",$str);
	$str=str_ireplace(chr(39),"&#39;",$str);
	$str=str_ireplace(chr(13),"<br />",$str);
	$str=str_ireplace("'","''",$str);
	$str=str_ireplace("select","sel&#101;ct",$str);
	$str=str_ireplace("join","jo&#105;n",$str);
	$str=str_ireplace("union","un&#105;on",$str);
	$str=str_ireplace("where","wh&#101;re",$str);
	$str=str_ireplace("insert","ins&#101;rt",$str);
	$str=str_ireplace("delete","del&#101;te",$str);
	$str=str_ireplace("update","up&#100;ate",$str);
	$str=str_ireplace("like","lik&#101;",$str);
	$str=str_ireplace("drop","dro&#112;",$str);
	$str=str_ireplace("create","cr&#101;ate",$str);
	$str=str_ireplace("modify","mod&#105;fy",$str);
	$str=str_ireplace("rename","ren&#097;me",$str);
	$str=str_ireplace("alter","alt&#101;r",$str);
	$str=str_ireplace("cast","ca&#115;",$str);
	return $str;
}


function msubstr($str, $start, $len) {
	$tmpstr = "";
	$strlen = $start + $len;
	for($i = 0; $i < $strlen; $i++) {
		if(ord(substr($str, $i, 1)) > 0xa0) {
			$tmpstr .= substr($str, $i, 2);
			$i++;
		} else
			$tmpstr .= substr($str, $i, 1);
	}
	return $tmpstr;
}

function getip()
{
	$ip = false;
	if(!empty( $_SERVER ["HTTP_CLIENT_IP"])) 
	{
		$ip = $_SERVER ["HTTP_CLIENT_IP"];
	}
	if (!empty( $_SERVER ['HTTP_X_FORWARDED_FOR'])) 
	{
		$ips = explode ( ", ",$_SERVER ['HTTP_X_FORWARDED_FOR']);
		if ($ip) 
		{
			array_unshift ($ips,$ip);
			$ip = FALSE;
		}
		for($i = 0; $i < count ( $ips ); $i ++)
		{
		if (!preg_match( "/^(10|172\.16|192\.168)\./i",$ips[$i]))
		{
		$ip =$ips[$i];
		break;
		}
		}
	}
	$ip_str=($ip?$ip:$_SERVER['REMOTE_ADDR']);
	$ip_arr=explode(',',$ip_str);
	return $ip_arr[0];
}

function CheckEmail($email)
{
	if (ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+",$email))
	{
		return true;
	}
	else
	{
		return false;    
	} 
}

function init_smarty()
{
	include_once(S_ROOT."source/smarty/Smarty.class.php");
	$tpl = new Smarty();
    $tpl->caching = false;
	$tpl->template_dir = S_ROOT."template/";
	$tpl->compile_dir = S_ROOT."template_c/";
	$tpl->cache_dir = S_ROOT."cache/";
	$tpl->left_delimiter = '<!--{';
	$tpl->right_delimiter = '}-->';
	return $tpl;
}

function echojson($msg = '', $status = 0, $dataarr = array()) {
    $arr = array (
        'msg'    => $msg,
        'status' => $status.''
    );
    if(!empty($dataarr)){
        $arr['data'] = $dataarr;
    }
	$str = json_encode($arr);
	echo $str;
	exit;
}

function randomkeys($length) 
{
	$key = null;
	$pattern = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ";
	for($i = 0; $i < $length; $i ++) 
	{
		$key .= $pattern {mt_rand ( 0, 35 )};
	}
	return $key;
}

function getbrowsertype()
{
	if (strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger'))
	{
		return "wx";
	}
	if(strpos($_SERVER ['HTTP_USER_AGENT'],'iPad')||strpos($_SERVER ['HTTP_USER_AGENT'],'iPhone')||strpos($_SERVER ['HTTP_USER_AGENT'],'Android')) 
	{ 
		$prom_username = $id;
		if(strpos($_SERVER ['HTTP_USER_AGENT'], 'Android'))
		{
			return "android";
		}
		else
		{
			return "iphone";	 
		}
		
	}
	return "pc";
}

function argsFilter()
{
	if($_POST)
	{
		foreach($_POST as $k=>$v)
		{
			if (is_array($v)) {
				foreach ($v as $key => $val) {
					$_POST[$k][$key]=inputFilter($val);
				}
				continue;
			}
			$_POST[$k]=inputFilter($v);
		}
	}
	if($_GET)
	{
		foreach($_GET as $k=>$v)
		{
			$_GET[$k]=inputFilter($v);
		}
	}
}

// 单例模式数据库操作函数  ---  阿里云
function getinstance() {
	require_once S_ROOT . 'source/db.php';
	return Mysqloper::getinstance();
}

function exec_db($sql) {
	$db = getinstance();
	return $db->exec_db($sql);
}

function getrecord($sql) {
	$db = getinstance();
	return $db->getrecord($sql);
}

function exec_db_insertid($sql) {
	$db = getinstance();
	return $db->exec_db_insertid($sql);
}

// 获取左侧栏目列表
function getColumn($gid,$uid,$ac,$op){
	$rule_arr = getrecord("SELECT name,rule_str FROM sys_admingroup WHERE id = '{$gid}' LIMIT 1");
	// 获取栏目对应的图标
	$iconv_list =array();
	$query =exec_db("SELECT rule_name,iconv FROM sys_adminrule_iconv");
	while ($row = mysqli_fetch_assoc($query)) {
		$iconv_list[$row['rule_name']] = $row['iconv'];
	}

	$query   =exec_db("SELECT * FROM sys_adminrule WHERE id IN ({$rule_arr['rule_str']}) AND status=1 ORDER BY sortby DESC,id ASC");
	$power   = array();  // 存放url地址
	$ui_list = array();  // 存放左侧显示列表
	$ui      = '';       // 左侧列表展示拼接
	$rule_id = 0;        // 当前url对应权限表id
	$crumb   = '';       // 面包屑
	$title   = '';       // 当前url地址页面title
	while ($row = mysqli_fetch_assoc($query)) {
		$power[$row['id']] =$row['ac'].'/'.$row['op'];
		if ($row['is_ui'] ==1) {
			$ui_list[$row['module']][] = $row;
		}
		if ($row['ac'] ==$ac && $row['op'] ==$op) {
			$title =$row['remark'];
			if ($ac && $op && $op !='list') {
				$remark =getrecord("SELECT remark FROM sys_adminrule WHERE ac='{$ac}' AND op='list'")['remark'];
				$crumb .='<span class="c-999 en">&gt;</span><a href="/admht.php?tp='.$ac.'&op=list"><span class="c-666">'.$remark.'</span></a><span class="c-999 en">&gt;</span><span class="c-666">'.$title.'</span>';
			}elseif ($ac && $op =='list') {
				$crumb .='<span class="c-999 en">&gt;</span><span class="c-666">'.$title.'</span>';
			}
		}
	}
	if (!in_array($ac.'/'.$op, $power)) {
		echo '权限不足';
		echo "<script>setTimeout('window.history.go(-1);',1000);</script>";die;
	}else{
		$rule_id =array_search($ac.'/'.$op, $power);
		$ctime =time();
		exec_db("INSERT INTO sys_adminlog (uid,rule_id,ctime) VALUES ('{$uid}','{$rule_id}','{$ctime}')");
	}
	foreach ($ui_list as $k => $v) {
		$iconv =isset($iconv_list[$k])?$iconv_list[$k]:'';
		$ui .='<dl id="menu-article">';
		$ui .='<dt><i class="Hui-iconfont">'.$iconv.'</i> '.$k.'<i class="Hui-iconfont menu_dropdown-arrow">&#xe6d5;</i></dt>';
		$ui .='<dd>';
		$ui .='<ul>';
		foreach ($v as $key => $val) {
			$ui .='<li><a href="admht.php?tp='.$val['ac'].'&op='.$val['op'].'" title="'.$val['remark'].'">'.$val['remark'].'</a></li>';
		}
		$ui .='</ul>';
		$ui .='</dd>';
		$ui .='</dl>';
	}
	return array('ui'=>$ui,'title'=>$title,'crumb'=>$crumb,'group_name'=>$rule_arr['name']);
}

// 后台分页
function multi_url($num, $perpage, $curpage, $mpurl) {
	$page      = 5;   // 需要显示的分页数量
	$multipage = '<div class="pageList">';
	// 拆分url地址
	$param = parse_url($mpurl); // 得到一维关联数组，键path=>地址  键query=>参数
	if (isset($param['query']) && '' != $param['query']) {
		// 将参数转换为一维数组  parse_str()：将字符串解析成多个变量，
		// 即将字符串解析多个变量存入数组$parse里面
		parse_str($param['query'], $parse);
		// 删除数组$parse里面下标为page的数据
		unset($parse['page']);
		if ($parse) { // 删除数组$parse下标为page的数据后，如果数组不为空，则说明存在下标为keyword的数据
			// 将转换为$parse的数组重新转换为对应的字符串
			$qurl = http_build_query($parse);
			$mpurl  = $param['path'] . '?' . $qurl . '&';
		} else { // 否则，说明数组$parse没有下标为keyword的数据，即没有其他参数了
			$mpurl = $param['path'] . '?';
		}
	} else {
		$mpurl = $param['path'] . '?';
	}

	$offset    = 2;
	$totalpage = @ceil($num / $perpage);

	if ($page > $totalpage) {
		$from = 1;
		$to   = $totalpage;
	} else {   
		// 2 3 4 5 6  $curpage=4   $from=2   $to=2+5-1=6
		$from = $curpage - $offset;
		$to   = $from + $page - 1;
		if ($from < 1) {   //  1 2 3 4 5  $curpage =2  $from=1  $to=1+5-1=5 
			$from = 1;
			$to   = $from + $page - 1;
		} elseif ($to > $totalpage) {  // 4 5 6 7 8  $curpage=8   $to=8   $from=8-5+1=4
			$from = $totalpage - $page + 1;
			$to   = $totalpage;
		}
	}

	$prevpage = $curpage - 1;
	$nextpage = $curpage + 1;

	if ($curpage <=1) {
		$multipage .= '<a href="javascript:void(0);">首页</a>';
		$multipage .= '<a href="javascript:void(0);">上一页</a>';
	} else {
		$multipage .= '<a href="'.$mpurl.'page=1">首页</a>';
		$multipage .= '<a href="'.$mpurl.'page='.$prevpage.'">上一页</a>';
	}

	for ($i = $from; $i <= $to; $i++) {
		if ($i == $curpage) {
			$multipage .= '<a class="active" href="javascript:void(0);">' . $i . '</a>';
		} else {
			$multipage .= '<a href="'.$mpurl.'page='.$i.'">'.$i.'</a>';
		}
	}
	if ($curpage >= $totalpage) {
		$multipage .= '<a href="javascript:void">下一页</a>';
		$multipage .= '<a href="javascript:void">末页</a>';
	} else {
		$multipage .= '<a href="'.$mpurl.'page='.$nextpage.'">下一页</a>';
		$multipage .= '<a href="'.$mpurl.'page='.$totalpage.'">末页</a>';
	}

	$multipage .='<span>每页'.$perpage.'条数据 | 总共'.$num.'条数据</span>';
	$multipage .= '</div>';
	return $multipage;
}

// 前端分页
function multi($num, $perpage, $curpage, $mpurl) {
	$page      = 5;   // 需要显示的分页数量
	$multipage = ' <div class="pageList">';
	// 拆分url地址
	$param = parse_url($mpurl); // 得到一维关联数组，键path=>地址  键query=>参数
	if (isset($param['query']) && '' != $param['query']) {
		// 将参数转换为一维数组  parse_str()：将字符串解析成多个变量，
		// 即将字符串解析多个变量存入数组$parse里面
		parse_str($param['query'], $parse);
		// 删除数组$parse里面下标为page的数据
		unset($parse['page']);
		if ($parse) { // 删除数组$parse下标为page的数据后，如果数组不为空，则说明存在下标为keyword的数据
			// 将转换为$parse的数组重新转换为对应的字符串
			$qurl = http_build_query($parse);
			$mpurl  = $param['path'] . '?' . $qurl . '&';
		} else { // 否则，说明数组$parse没有下标为keyword的数据，即没有其他参数了
			$mpurl = $param['path'] . '?';
		}
	} else {
		$mpurl = $param['path'] . '?';
	}

	$offset    = 2;
	$totalpage = @ceil($num / $perpage);

	if ($page > $totalpage) {
		$from = 1;
		$to   = $totalpage;
	} else {   
		// 2 3 4 5 6  $curpage=4   $from=2   $to=2+5-1=6
		$from = $curpage - $offset;
		$to   = $from + $page - 1;
		if ($from < 1) {   //  1 2 3 4 5  $curpage =2  $from=1  $to=1+5-1=5
			//$to   = $curpage + 1 - $from;   
			$from = 1;
			$to   = $from + $page - 1;
			// if ($to - $from < $page) {
			// 	$to = $page;
			// }
		} elseif ($to > $totalpage) {  // 4 5 6 7 8  $curpage=8   $to=8   $from=8-5+1=4
			$from = $totalpage - $page + 1;
			$to   = $totalpage;
		}
	}

	$prevpage = $curpage - 1;
	$nextpage = $curpage + 1;

	if ($curpage <=1) {
		$multipage .= '<a href="javascript:void(0);" class="prev">首页</a>"';
		$multipage .= '<a href="javascript:void(0);" class="prev">上一页</a>"';
	} else {
		$multipage .= '<a href="'.$mpurl.'page=1" class="prev">首页</a>';
		$multipage .= '<a href="'.$mpurl.'page='.$prevpage.'" class="prev">上一页</a>';
	}

	for ($i = $from; $i <= $to; $i++) {
		if ($i == $curpage) {
			$multipage .= '<a class="active" href="javascript:void(0);">' . $i . '</a>';
		} else {
			$multipage .= '<a href="'.$mpurl.'page='.$i.'">'.$i.'</a>';
		}
	}
	if ($curpage >= $totalpage) {
		$multipage .= '<a href="javascript:void" class="prev">下一页</a>';
		$multipage .= '<a href="javascript:void" class="next">末页</a>';
	} else {
		$multipage .= '<a href="'.$mpurl.'page='.$nextpage.'" class="prev">下一页</a>';
		$multipage .= '<a href="'.$mpurl.'page='.$totalpage.'" class="next">末页</a>';
	}

	$multipage .= "<span><em>共</em><input type='text' id='pageNum' value='" . $curpage . "' name='' class='tg-page-num'><em>/" . $totalpage . "页</em><input type='button' id='autoPage' name='' value='跳转' class='tg-page-btn mar_l_10'></span>";

	$multipage .= '</div>';
	$multipage .= "<script>
						document.getElementById('autoPage').onclick = function(){
							var pageNum=document.getElementById('pageNum').value;
							location.href='/{$mpurl}page='+pageNum;
						}
		              </script>";

	return $multipage;
}



